import re

from django.shortcuts import render
from user.models import User
from django.views import View
from django.http import JsonResponse
import json

class UsernameCountView(View):
    """用户名数量"""
    def get(self, request, username):
        """
        获取用户名的数量
        :param request: 请求对象
        :param username: 用户名
        :return: 返回用户名数量
        """

        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return JsonResponse({'username': '用户名不满足要求'}, status=400)



        count = User.objects.filter(username=username).count()
        return JsonResponse({'count': count, 'username': username}, status=200)


class RegisterView(View):
    """注册"""
    def post(self, request):
        """
        用户注册
        :param request: 请求对象
        :return: 返回注册结果
        """
        # 这里可以添加注册逻辑
        body_bytes = request.body
        body_str = body_bytes.decode()
        body_dict = json.loads(body_str)

        username = body_dict.get('username')
        password = body_dict.get('password')
        password2 = body_dict.get('password2')
        mobile = body_dict.get('mobile')
        allow = body_dict.get('allow')

        #校验参数
        if not all([username, password, password2, mobile, allow]):
            return JsonResponse({'message': '请填写完整'}, status=400)
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return JsonResponse({'message': '用户名不满足要求'}, status=400)
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return JsonResponse({'message': '密码不满足要求'}, status=400)
        if password != password2:
            return JsonResponse({'message': '两次密码不一致'}, status=400)
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'message': '请输入正确的手机号'}, status=400)
        if not allow:
            return JsonResponse({'message': '请勾选同意协议'}, status=400)
        user = User.objects.create_user(username=username, password=password, mobile=mobile)

        return JsonResponse({'message': '注册成功'}, status=201)

    def get(self, request):
        """
        获取注册页面
        :param request: 请求对象
        :return: 返回注册页面
        """
        return render(request, 'register.html')